package com.totoro.dubbo.consumer.config;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ConsumerConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * Created by Niki on 2018/7/2 9:04
 */
@Configuration
public class DubboConfig {
    @Value("${dubbo.application.name}")
    private String applicationName;
    @Value("${dubbo.application.owner}")
    private String owner;

    @Value("${dubbo.registry.protocol}")
    private String registryProtocol;
    @Value("${dubbo.registry.address}")
    private String registryAddress;
    @Value("${dubbo.registry.user}")
    private String registryUser;
    @Value("${dubbo.registry.password}")
    private String registryPassword;

    @Value("${dubbo.protocol}")
    private String protocol;
    @Value("${dubbo.protocol.port}")
    private int port;
    @Value("${dubbo.protocol.threads}")
    private int threads;

    @Bean
    public ApplicationConfig applicationConfig() {
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName(this.applicationName);
        applicationConfig.setOwner(this.owner);

        return applicationConfig;
    }

    @Bean
    public RegistryConfig registryConfig() {
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setProtocol(this.registryProtocol);
        registryConfig.setAddress(this.registryAddress);
        if (!StringUtils.isEmpty(this.registryUser)) {
            registryConfig.setUsername(this.registryUser);
        }
        if (!StringUtils.isEmpty(this.registryPassword)) {
            registryConfig.setPassword(this.registryPassword);
        }

        return registryConfig;
    }

    @Bean
    public ProtocolConfig protocolConfig() {
        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.setName(this.protocol);
        protocolConfig.setPort(this.port);
        protocolConfig.setThreads(this.threads);
        return protocolConfig;
    }

    @Bean
   public ConsumerConfig consumerConfig(){
        ConsumerConfig consumerConfig = new ConsumerConfig();
        consumerConfig.setTimeout(3000);
        return consumerConfig;
    }
}
